package org.alvin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.Map;

public class ItsmJsonTest {

    public static void main(String[] args) throws IOException {
        byte[] buff = Files.readAllBytes(Paths.get("D:", "itsm_service_dir.json"));
        JSONObject jsonObject = JSON.parseObject(new String(buff));
        JSONArray array = jsonObject.getJSONArray("obj");
        JSONObject treeObj = new JSONObject();
        for (int i = 0; i < array.size(); i++) {
            JSONObject node = array.getJSONObject(i);
            JSONObject newNode = new JSONObject();
            newNode.put("id",node.getString("id"));
            newNode.put("pId",node.getString("pId"));
            newNode.put("name",node.getString("name"));
            treeObj.put(node.getString("id"), newNode);
        }
//        System.out.println(treeObj);
        //
//        JSONObject tree = new JSONObject();
        for (String key : treeObj.keySet()) {
            JSONObject node = treeObj.getJSONObject(key);

                String pid = node.getString("pId");
                JSONObject parent = treeObj.getJSONObject(pid);
                if(parent == null){
                    continue;
                }
                if(!parent.containsKey("children")){
                    parent.put("children",new JSONArray());
                }
                node.put("hasP",true);
                parent.getJSONArray("children").add(node);

        }
        LinkedList<JSONObject> linkedList = new LinkedList<>();
        for(String key: treeObj.keySet()){
            JSONObject tm = treeObj.getJSONObject(key);
            if(tm.containsKey("hasP")){
                continue;
            }
            linkedList.add(tm);
        }
        //
        while(!linkedList.isEmpty()){
            JSONObject node = linkedList.removeFirst();
            if(node.containsKey("children")){
                JSONArray children =  node.getJSONArray("children");
                for(int i = 0 ; i <children.size();i++){
                    JSONObject child = children.getJSONObject(i);
                    child .put("name",node.getString("name")+"/" + child.getString("name"));
                    linkedList.add(child);
                }
                continue;
            }
            System.out.println(node.getString("name"));
        }
    }
}
